package com.inhim.pjhim.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;

import com.inhim.pjhim.R;
import com.inhim.pjhim.app.BaseActivity;
import com.inhim.pjhim.app.MyApplication;
import com.inhim.pjhim.dowloadfile.download.DownloadInfo;
import com.inhim.pjhim.fragment.FoundFragment;
import com.inhim.pjhim.fragment.MyFragment;
import com.inhim.pjhim.fragment.VideoFragment;
import com.inhim.pjhim.utils.StatusBarUtils;
import com.inhim.pjhim.utils.Utils;
import com.inhim.pjhim.view.BToast;
import com.inhim.pjhim.view.NoScrollViewPager;
import com.mob.MobSDK;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class HomeActivity extends BaseActivity implements View.OnClickListener {
    private NoScrollViewPager viewPager;
    private ArrayList<Fragment> fs;
    private RadioButton radio1;
    private RadioButton radio2,radio3;
    private ImageView iv_start;
    final int SPLASH_DISPLAY_LENGHT = 2000;
    private Handler mMainHandler=new Handler();
    @Override
    public Object offerLayout() {
        return R.layout.activity_home;
    }

    @Override
    public void onBindView() {
        initView();
        setDownloadLisStatus();
        if (Utils.isExistNetwork(this)) {
            mMainHandler.postDelayed(() -> {
                iv_start.setVisibility(View.GONE);
            }, SPLASH_DISPLAY_LENGHT);
        } else {
            Utils.displayToast(this, "请检查网络……");
        }
        rxPermissionWriteAndRead();
        MobSDK.submitPolicyGrantResult(true,null);
    }


    @Override
    public void destory() {
        mMainHandler.removeCallbacksAndMessages(null);
    }

    private void setDownloadLisStatus() {
        try {
            List<DownloadInfo> myBusinessInfos = LitePal.findAll(DownloadInfo.class);
            if(myBusinessInfos!=null){
                for(int i=0;i<myBusinessInfos.size();i++){
                    DownloadInfo downloadInfo=myBusinessInfos.get(i);
                    downloadInfo.setDownloadStatus(DownloadInfo.DOWNLOAD_PAUSE);
                    downloadInfo.save();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 按返回键退出
    long previous = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == 4)
            if (System.currentTimeMillis() - previous > 2000) {
                BToast.showText("再按一次退出");
                previous = System.currentTimeMillis();
            } else {
                System.exit(0);
            }
        return true;
    }
    private void rxPermissionWriteAndRead() {
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {
                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (HomeActivity.this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    HomeActivity.this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                } else {
                    //这里就是权限打开之后自己要操作的逻辑
                }
            }
        }
       /* RxPermissions rxPermissions = new RxPermissions(HomeActivity.this);
        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(granted -> {
            if (granted) {
            } else {
                BToast.showText("读写权限被拒绝",true);
            }
        });*/
    }
    private void initView() {
        View navigationView = findViewById(R.id.navigationView);
        ViewGroup.LayoutParams navigationlayoutParams = navigationView.getLayoutParams();
        if(StatusBarUtils.isHaveNativBar(this)){
            navigationlayoutParams.height = MyApplication.getNavigationBarHeight();
        }else{
            navigationlayoutParams.height = 0;
        }
        iv_start=findViewById(R.id.iv_start);
        viewPager=findViewById(R.id.viewPager);
        viewPager.setNoScroll(true);
        radio1=findViewById(R.id.radio1);
        radio2=findViewById(R.id.radio2);
        radio3=findViewById(R.id.radio3);
        radio1.setOnClickListener(this);
        radio2.setOnClickListener(this);
        radio3.setOnClickListener(this);
        fs=new ArrayList<>();
        MyFragment myFragment=new MyFragment();
        myFragment.setFinishActivityLinestener(() -> {
            finish();
        });
        fs.add(new VideoFragment());
        fs.add(new FoundFragment());
        fs.add(myFragment);
        FragmentManager fm=getSupportFragmentManager();
        MyPagerAdapter adapter=new MyPagerAdapter(fm);
        viewPager.setAdapter(adapter);
        viewPager .setOffscreenPageLimit(2);
        setListener();
    }
    private void setListener() {
        // TODO Auto-generated method stub
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        radio1.setChecked(true);
                        break;
                    case 1:
                        radio3.setChecked(true);
                        break;
                    case 2:
                        radio2.setChecked(true);
                        break;
                }

            }
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }
            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.radio1:
                viewPager.setCurrentItem(0);
                break;
            case R.id.radio2:
                viewPager.setCurrentItem(2);
                break;
            case R.id.radio3:
                viewPager.setCurrentItem(1);
                break;
        }
    }

    /**
     * 自定义适配器  FragmentPagerAdapter
     */
    class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int arg0) {
            return fs.get(arg0);
        }

        @Override
        public int getCount() {
            return fs.size();
        }
    }
}
